package com.boot2.core.utils;

import com.boot2.core.exception.AesException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Scanner;

/*
 * AES对称加密和解密
 */
public class AesUtil {

    /**
     * aes+base64加密
     *
     * @param key
     * @param content
     * @return
     */
    public static String aesEncodeWithBase64(String key, String content) {
        String str = aesEncode(key, content);
        str = Base64StringUtil.getBase64(str);
        return str;
    }

    /**
     * aes+base64解密
     *
     * @param key
     * @param content
     * @return
     */
    public static String aesDecodeWithBase64(String key, String content) {
        String str = Base64StringUtil.getFromBase64(content);
        str = aesDecode(key, str);
        return str;
    }

    /*
     * 加密 1.构造密钥生成器 2.根据ecnodeRules规则初始化密钥生成器 3.产生密钥 4.创建和初始化密码器 5.内容加密 6.返回字符串
     */
    public static String aesEncode(String key, String content) {
        try {
            byte[] aesByte = aesEncode(key, content.getBytes("UTF-8"));
            // 10.将加密后的数据转换为字符串
            // 这里用Base64Encoder中会找不到包
            // 解决办法：
            // 在项目的Build path中先移除JRE System Library，再添加库JRE System Library，重新编译后就一切正常了。
            String aesEncode = new String(new BASE64Encoder().encode(aesByte));
            // 11.将字符串返回
            return aesEncode;
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedEncodingException | IllegalBlockSizeException
                | BadPaddingException e) {
            throw new AesException("加密失败", e);
        }
    }

    public static byte[] aesEncode(String key, byte[] content) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
            UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
        // 1.构造密钥生成器，指定为AES算法,不区分大小写
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        // 2.根据ecnodeRules规则初始化密钥生成器
        // 生成一个128位的随机源,根据传入的字节数组
        // keygen.init(128, new SecureRandom(encodeRules.getBytes()));

        // 兼容linux
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        keygen.init(128, random);

        // 3.产生原始对称密钥
        SecretKey originalKey = keygen.generateKey();
        // 4.获得原始对称密钥的字节数组
        byte[] raw = originalKey.getEncoded();
        // 5.根据字节数组生成AES密钥
        SecretKey keySpec = new SecretKeySpec(raw, "AES");
        // 6.根据指定算法AES自成密码器
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        // 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
        // 9.根据密码器的初始化方式--加密：将数据加密
        byte[] aesByte = cipher.doFinal(content);
        return aesByte;
    }

    /*
     * 解密 解密过程： 1.同加密1-4步 2.将加密后的字符串反纺成byte[]数组 3.将加密内容解密
     */
    public static String aesDecode(String key, String content) {
        try {
            byte[] contentByte = new BASE64Decoder().decodeBuffer(content);
            byte[] decodeByte = aesDecode(key, contentByte);
            String aesDecode = new String(decodeByte, "utf-8");
            return aesDecode;
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | IOException e) {
            e.printStackTrace();
            throw new AesException("解密失败", e);
        }
    }

    private static byte[] aesDecode(String key, byte[] contentByte)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        // 1.构造密钥生成器，指定为AES算法,不区分大小写
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        // 2.根据ecnodeRules规则初始化密钥生成器
        // 生成一个128位的随机源,根据传入的字节数组
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        keygen.init(128, random);

        // keygen.init(128, new SecureRandom(key.getBytes()));
        // 3.产生原始对称密钥
        SecretKey originalKey = keygen.generateKey();
        // 4.获得原始对称密钥的字节数组
        byte[] raw = originalKey.getEncoded();
        // 5.根据字节数组生成AES密钥
        SecretKey key0 = new SecretKeySpec(raw, "AES");
        // 6.根据指定算法AES自成密码器
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
        cipher.init(Cipher.DECRYPT_MODE, key0);
        // 8.将加密并编码后的内容解码成字节数组
        /*
         * 解密
         */
        byte[] decodeByte = cipher.doFinal(contentByte);
        return decodeByte;
    }

    public static String getCpuId() {
        Process process = null;
        OutputStream outputStream = null;
        try {
            process = Runtime.getRuntime().exec(
                    new String[]{"wmic", "cpu", "get", "ProcessorId"});
            outputStream = process.getOutputStream();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Scanner sc = new Scanner(process.getInputStream());
        String property = sc.next();
        String serial = sc.next();
        System.out.println(property + ": " + serial);
        String encode = MD5.encode(serial, 5);
        return encode;
    }

    public static void main(String[] args) {
//		// String encodeRules = "zhangweilin_productType_hl_ark_iot_2017-12-22
//		// 17:36:52";
//		// String content = "12";
////		String encodeRules = "arkiarkiarkiarkixx";
////		String content = "123456789";
//		String encodeRules = "11111111111111111111111111111111";
//		System.out.println("encodeRules.length = " + encodeRules.length());
//		String content = "hello";
//		/*
//		 * 加密
//		 */
//		String str = aesEncode(encodeRules, content);
//		System.out.println("根据输入的规则" + encodeRules + "加密后的密文是:" + str);
//
//		/*
//		 * 解密
//		 */
//		String str2 = aesDecode(encodeRules, str);
//		System.out.println("根据输入的规则" + encodeRules + "解密后的明文是:" + str2);
//
//		System.out.println("以下为经过base64包装的");
//
//		String str3 = aesEncode(encodeRules, content);
//		System.out.println("str3: " + str3);
//		String str4 = Base64StringUtil.getBase64(str3);
//		System.out.println("str4: " + str4);
//
////		str4 = "YWdOU1o1YUxDdmwyQzNtWU83eDNYdz09";
////		String str5 = Base64StringUtil.getFromBase64(str4);
////		System.out.println("str5: " + str5);
////		String str6 = aesDecode(encodeRules, str5);
////		System.out.println("str6: " + str6);
//
//		String key2 = "12365478998788";
//		// byte[] keyHeaderByte = new byte[] { (byte) 0xA5, (byte) 0x4B, (byte) 0x45,
//		// (byte) 0x59,
//		// (byte) 0xAA ,0x35};
//		byte[] keyHeaderByte = "hello world你好呀这个怎么可能呢k ".getBytes("UTF-8");
//		String keyHeaderByteStr = Arrays.toString(keyHeaderByte);
//		System.out.println("byte加密前: " + keyHeaderByteStr);
//
//		byte[] keyHeaderByte2 = aesEncode(key2, keyHeaderByte);
//		String keyHeaderByte2Str = Arrays.toString(keyHeaderByte2);
//		System.out.println("byte加密后: " + keyHeaderByte2Str);
//
//		byte[] keyHeaderByte3 = aesDecode(key2, keyHeaderByte2);
//		String keyHeaderByte3Str = Arrays.toString(keyHeaderByte3);
//		System.out.println("byte解密后: " + keyHeaderByte3Str);
//
//		String keyHeaderByte3Str4 = new String(keyHeaderByte3, "UTF-8");
//		System.out.println("byte解密后字符串: " + keyHeaderByte3Str4);
//
//		String keyHeaderByte3Str16Hex = ByteUtils.hexBytes2HexString(keyHeaderByte3);
//		System.out.println("byte解密后16进制字符串: " + keyHeaderByte3Str16Hex);
//
////		String keyHeaderByte3Str16Hex2 = ByteUtils.hexBytes2HexString2(keyHeaderByte3);
////		System.out.println("byte解密后16进制字符串: " + keyHeaderByte3Str16Hex2);


        String encodeRules = getCpuId();
        System.out.println("encodeRules " + encodeRules);
        String content = args[0];

        /*
         * 加密
         */
        String str = aesEncode(encodeRules, content);
        System.out.println("根据输入的规则" + encodeRules + "加密后的密文是:" + str);

        /*
         * 解密
         */
        String str2 = aesDecode(encodeRules, str);
        System.out.println("根据输入的规则" + encodeRules + "解密后的明文是:" + str2);

    }

}